# -*- coding:UTF-8 -*-
import random
import time
import traceback

from db import *
from spider_xue.logger import logging
from spider_xue.new_ip import new_ip_obj, headers_list
from spider_xue.settings import ERROR, INFO, NINE_TIME_STAMP, URL5
from spider_xue.spider import Snowball
from spider_xue.utils import send_msg


def do_five(account, stocks, workQueueIP):
    snow = Snowball(son_work_five)
    iipp = workQueueIP.get()
    snow.headers['user-agent'] = random.choice(headers_list)
    snow.headers['cookie'] = account['cookies']
    snow.session.headers = snow.headers
    snow.session.proxies = {"http": "http://{}".format(iipp["ip"])}
    fail = []
    tt = int(time.time())
    start = str(tt + 3600) + "000"
    # end = str(int((tt + 10 - NINE_TIME_STAMP) / 60))
    end = '300'
    i = 0
    nine = settings_db.find_one({"name": 'nine_timestamp'})
    for i in range(len(stocks)):
        try:
            flag = snow.get_res_together_no_save(
                URL5, stocks[i], start, end, data_five_db, nine['timestamp'])
            # flag = snow.get_res_5(stocks[i]['symbol'], start, end)
            time.sleep(0.5)
            if not flag:
                fail.append(stocks[i])
        except Exception as e:
            if 'HTTPConnectionPool' not in str(e):
                traceback.print_exc()
            err = str(e) if 'HTTPConnectionPool' not in str(
                e) else "HTTPConnectionPool problem"
            logging.error(
                f"mission Exception {stocks[i]['symbol']} {err} --- use IP: {iipp['ip']} ")
            # new_ip_obj.delete_one(iipp)
            return fail + stocks[i:]
    return fail


def son_work_five(x, stock, timestamp):
    symbol = x['symbol']
    item = x['item']
    history = history_five_db.find_one({"symbol": symbol})
    if not history:
        five_time_list = []
        five_time_dict = {}
    else:
        five_time_list = history.get('five_time_list', [])
        five_time_dict = history.get('five_time_dict', {})

    r = len(item)
    for i in range(r):
        d = item[i]
        tt = time.localtime(int(d[0] / 1000))
        itt = time.strftime('%Y-%m-%d', tt)
        set_value_five(five_time_list, five_time_dict, itt, symbol, d[9])
    lll = 5
    if len(five_time_list) < 5:
        lll = len(five_time_list)
    tt = [five_time_dict[five_time_list[zx]] for zx in range(0-lll, 0)]
    stock_db.update_one({
        "symbol": symbol},
        {"$set": {
            "p5": round(sum(tt) / 5)
        }})
    update_his(
        history_five_db, symbol,
        {
            "five_time_list": five_time_list,
            "five_time_dict": five_time_dict,
        }
    )


def set_value_five(time_list, time_dict, itt, symbol, cal, ti=None, ttt=None):
    if time_list:
        if itt not in time_list:
            if itt > time_list[-1]:
                time_dict[itt] = cal
                time_list.append(itt)
            else:
                send_msg("### 时间不对拉！！！尼玛 %s %s" % (itt, symbol))
        else:
            if time_dict[itt] < cal:
                time_dict[itt] = cal
    else:
        time_dict[itt] = cal
        time_list.append(itt)


def update_his(his, symbol, key):
    his.update_one({"symbol": symbol}, {"$set": key}, upsert=True)
